package org.example.controller;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.example.mapper.LogMapper;
import org.example.pojo.LogVO;
import org.example.pojo.PageBean;
import org.example.pojo.ScanHistoryVO;
import org.example.utils.Loggable;
import org.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/api/log")
public class LogController {
    @Autowired
    private LogMapper logMapper;
    @PostMapping()
    public Result addLog(@RequestBody LogVO logVO, HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        logVO.setIp(ipAddress);
        logMapper.addLog(logVO);
        return Result.success();
    }
    @Loggable(action = "获取日志列表")
    @GetMapping()
    public Result logList(@RequestParam(defaultValue = "1") Integer page,
                          @RequestParam(defaultValue = "10") Integer size, String keywords, String start, String end) {
        PageHelper.startPage(page, size);
        List<LogVO> logList = logMapper.logList(keywords, start, end);
        Page<LogVO> p = (Page<LogVO>) logList;
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return Result.success(pageBean);
    }
}
